package com.backend.system.service.processors.user;

import cn.hutool.core.collection.CollUtil;
import com.backend.system.beans.user.UserGrantRolesReq;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.RoleUser;
import com.backend.system.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户分配角色处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.USER_GRANT_ROLES)
public class UserGrantRolesProcessor extends AbstractProcessorTemplate<UserGrantRolesReq, Boolean> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<UserGrantRolesReq> context) {
        UserGrantRolesReq req = context.getData();
        Long userId = req.getUserId();
        List<Long> roleIds = req.getRoleIds();
        String remark = req.getRemark();

        // 查用户已拥有的角色
        List<RoleUser> roleUsers = roleUserService.getRoleUsersByUserId(userId);
        Set<Long> grantedRoleIdSet = Collections.emptySet();
        if (CollUtil.isNotEmpty(roleUsers)) {
            grantedRoleIdSet = roleUsers.stream().map(RoleUser::getRoleId).collect(Collectors.toSet());
        }

        Set<Long> roleIdSet = new HashSet<>();
        // 当前用户ID被设置过角色
        if (CollUtil.isNotEmpty(grantedRoleIdSet)) {
            for (Long roleId : roleIds) {
                if (grantedRoleIdSet.contains(roleId)) {
                    continue;
                }
                roleIdSet.add(roleId);
            }
        } else {
            // 当前用户ID没有被设置过角色
            roleIdSet = new HashSet<>(roleIds);
        }

        List<RoleUser> roleUserList = new ArrayList<>();
        for (Long id : roleIdSet) {
            RoleUser roleUser = new RoleUser();
            roleUser.setRoleId(id);
            roleUser.setUserId(userId);
            if (StringUtil.isNotBlank(remark)) {
                roleUser.setRemark(remark);
            }
            roleUserList.add(roleUser);
        }

        return roleUserService.saveBatch(roleUserList);
    }
}
